import * as faceapi from "face-api.js";

main()

let descriptors = { desc1: null, desc2: null }
const threshold = 0.6

async function main(){
    
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.loadFaceLandmarkModel('http://127.0.0.1:8888/weights')
    await faceapi.loadFaceRecognitionModel('http://127.0.0.1:8888/weights')

    let select1Dom = document.getElementById('select1')
    let select2Dom = document.getElementById('select2')
    drawSelect(select1Dom)
    drawSelect(select2Dom)
    drawImage(1,select1Dom, select1Dom.value)
    drawImage(2,select2Dom, select2Dom.value)

    select1Dom.addEventListener('change',function(e){
        drawImage(1,select1Dom, e.target.value)
    })
    select2Dom.addEventListener('change',function(e){
        drawImage(2,select2Dom, e.target.value)
    })


    closeLoading()
}

//显示两个face的距离值
function updateResult(){
    if(!descriptors.desc1 || !descriptors.desc2){return}
    const distance = faceapi.utils.round(
        faceapi.euclideanDistance(descriptors.desc1, descriptors.desc2)
    )

    let text = distance
    let bgColor = '#ffffff'
    if (distance > threshold) {
      text += ' (no match)'
      bgColor = '#ce7575'
    }

    let dom = document.getElementById('distance')
    dom.value = text 
    dom.style.backgroundColor = bgColor
}

// 填充image
async function drawImage(which,dom, value){
    let arr = value.split('-')
    let uri = 'http://127.0.0.1:8888/images/'+arr[0]+'/'+arr[0]+arr[1]+'.png'
    let currentImg = await faceapi.fetchImage(uri)
    const image = dom.parentNode.parentNode.querySelector('img')
    image.src = currentImg.src

    descriptors[`desc${which}`] = await faceapi.computeFaceDescriptor(image)
    updateResult()
}

// 填充select
function drawSelect(dom){
    const classes = ['amy', 'bernadette', 'howard', 'leonard', 'penny', 'raj', 'sheldon', 'stuart']
    
    const indices = [1, 2, 3, 4, 5]
    let items = []
    classes.sort((a,b)=>{
        return Math.random()>0.5?-1:1
    })
    classes.forEach(name=>{
        indices.forEach(index=>{
            items.push({index,name})
        })
    })

    let options = items.map(v=>{
        return `<option value="${v.name}-${v.index}">${v.name}-${v.index}</option>`
    }).join('')

    dom.innerHTML = options
}